package org.smart4j.framework.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Wenxin on 2017/2/26.
 */
public class JsonUntil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUntil.class);

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static String toJson(Object model) throws JsonProcessingException {
        String json = null;
        try {

            json = OBJECT_MAPPER.writeValueAsString(model);
        } catch (Exception e) {
            LOGGER.debug("convert to json failure: ", e);
        }
        return json;
    }

    public static <T> T fromJson(String json, Class<?> cls) throws JsonProcessingException {
        T result = null;
        try {
            result = OBJECT_MAPPER.readValue(json.getBytes(), (Class<T>) cls);
        } catch (Exception e) {
            LOGGER.debug("{} convert to {} failure: {}", json, cls.getName(), e);
        }
        return result;
    }
}
